// 单元格点击
// 1 获取所有的单元格列表
let cells = document.querySelectorAll('.cell');
//获取游戏面板
let bord = document.querySelector('#bord')!
//获取获胜信息面板
let message = document.querySelector('#message') as HTMLDivElement
// 获取获胜信息文本元素
let winner = document.querySelector('#winner') as HTMLSpanElement
//判赢数组
let winsArr = [
  [0,1,2],[3,4,5],[6,7,8],
  [0,3,6],[1,4,7],[2,5,8],
  [0,4,8],[2,4,6]
]  
//获取重新开始按钮元素
let restart = document.querySelector('#restart') as HTMLButtonElement
//定义记录点击次数
let steps:number;

//设置枚举类型
enum Player {
  X = 'x',
  O = 'o'
}
let currentPlayer:Player;
// 2 遍历单元格列表，给每个单元格添加点击事件
// cells.forEach(function (item){
//   let cell = item as HTMLDivElement;
//   cell.addEventListener('click',clickCell,{once:true})
// })
startGame()
// 点击事件函数
function clickCell(event:MouseEvent){
    let target = event.target as HTMLDivElement;
    target.classList.add(currentPlayer)
    //点击次数加一
    steps++
    //调用判赢函数获取判赢结果
    let isWin = checkWin(currentPlayer)
    // 判断结果
    if(isWin){
      message.style.display = 'block'
      winner.innerText = currentPlayer+'赢了！'
      return
    }
    //当点击次数为9,并且没有产生胜利,此时为平局
    if(steps === 9){
        message.style.display = 'block'
      winner.innerText = '平局'
      return
    }
    // 是否切换玩家
    currentPlayer = currentPlayer === Player.X ? Player.O : Player.X;
    //下一步提示信息
    bord.classList.remove(Player.X,Player.O)
    bord.classList.add(currentPlayer)


  }

  // 封装判赢函数
  function checkWin(player:Player):boolean{
     // 获取每种获胜情况
   return winsArr.some(function (item){
      // 获取每种获胜情况对应的3个单元格元素
      let cell1 = cells[item[0]]
      let cell2 = cells[item[1]]
      let cell3 = cells[item[2]]
      // 判断三个单元格是否同时包含相同的类名
      if(
        hasClass(cell1,player) &&
        hasClass(cell2,player) &&
        hasClass(cell3,player)
        
      ){
        return true
      }
        return false;
      
    })

  }

  // 封装判断指定元素是否包含指定类名
  function hasClass(el:Element,name:string):boolean{
    return el.classList.contains(name)
  }

  // 重新开始
  restart.addEventListener('click',startGame)
    // 重新开始回调函数
  function startGame(){
    // 隐藏获胜信息
    message.style.display = 'none';
    // 重置下棋次数
    steps = 0;
    //重置默认玩家为x
    currentPlayer = Player.X;
    // 重置下棋提示为x
    bord.classList.remove(Player.X,Player.O);
    bord.classList.add(Player.X);
    // 遍历棋盘元素
    cells.forEach(function(item){
      let cell = item as HTMLDivElement;
      // 清空棋盘
      cell.classList.remove(Player.X,Player.O)
      // 移除单元格单击事件，重新绑定单击事件
      cell.removeEventListener('click',clickCell)
      cell.addEventListener('click',clickCell,{once:true})
    })
  }